<!DOCTYPE html>
<html lang="zh">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>09 demo</title>
</head>

<body>
    <p style="font-size: large;">在控制台中检查输出</p>
    <h1>1</h1>
    <h1>1</h1>
    <h1>1</h1>
    <h1>1</h1>
    <h1>1</h1>
    <h1>1</h1>
    <h1>1</h1>
    <h1>1</h1>
    <h1>1</h1>
    <h1>1</h1>
    <h1>1</h1>
    <h1>1</h1>
    <h1>1</h1>
    <h1>1</h1>
    <h1>1</h1>
    <h1>1</h1>
    <h1>1</h1>
    <h1>1</h1>
    <h1>1</h1>
    <h1>1</h1>
    <h1>1</h1>
    <h1>1</h1>
    <h1>1</h1>
    <h1>1</h1>
    <h1>1</h1>
    
    <script>
        function debounce(fn, delay) {
            let timer = null // 借助闭包
            console.log("令 timer 为 null");  // 该代码只会在网页最初加载时执行一次

            return function () {
                if (timer) {
                    console.log("进入timer");
                    clearTimeout(timer);
                }
                timer = setTimeout(fn, delay) // 简化写法
                console.log("timer id:", timer);
            }
        }

        // 然后是旧代码
        function showTop() {
            var scrollTop = document.documentElement.scrollTop;
            console.log('滚动条位置：' + scrollTop);
        }
        window.onscroll = debounce(showTop, 3000)
    </script>
</body>

</html>